/*
 * @Descripttion:
 * @version:
 * @Author: LiLin7
 * @Date: 2021-04-05 20:28:48
 * @LastEditors: LiLin7
 * @LastEditTime: 2021-04-07 22:24:41
 */
export async function importHtml(entry) {
  let content = await loadSource(entry)
  const ATTR_RE = /["'=\w\s]*/.source;
  const ret = await parseScript(content)
  const cssRet = await parseCss(content, entry)
  parseBody(content)
  console.log(content, ret, cssRet);
  // 1、加载子应用入口
  // 正则
  // 解析css
  async function parseCss(content, entry) {
    const CSS_LINK_RE = new RegExp('<link' + ATTR_RE + 'href="([^"]+.css[^"]*)"' + ATTR_RE + '>', 'g')
    const STYLE_CONTENT_RE = /<style>([^<]*)<\/style>/
    const CSS_RE = new RegExp('(?:' + CSS_LINK_RE.source + ')|(?:' + STYLE_CONTENT_RE.source + ")", 'g')
    let match
    let css = []
    let styles = []
    while ((match = CSS_RE.exec(content))) {
      let style
      if (match[1]) {
        style = match[1].trim()
        style && css.push(style)
      } else if (match[2]) {
        style = match[2].trim()
        style && styles.push(style)
      }
    }
    return { css, styles }
  }
  // 解析html
  function parseBody(content) {
    const BODY_RE = /<body>([\w\W]*)<\/body>/g;
    const SCRIPT_RE = /<script["'=\w\s]*>[\s\S]*<\/script>/g;
    let bodyContent = content.match(BODY_RE)
    console.log(bodyContent);
  }
  // 解析Javascript
  async function parseScript(content) {
    const SCRIPT_CONTENT_RE = new RegExp('<script' + ATTR_RE + '>([\\w\\W]*)</script>', 'g');
    const SCRIPT_SRC_RE = new RegExp('<script' + ATTR_RE + 'src="(.+)">', 'g');
    let scripts = []
    let scriptUrls = []
    let match
    while (match = SCRIPT_CONTENT_RE.exec(content)) {
      const script = match[1].trim();
      script && scripts.push(script);
    }
    while (match = SCRIPT_SRC_RE.exec(content)) {
      const url = match[1].trim();
      url && scriptUrls.push(url);
    }
    let promiseAll = await Promise.all(scriptUrls.map(url => {
      let u = url.startsWith('http:') || url.startsWith('https:') ? url : entry + url;
      return loadSource(u)
    }))
    scripts = promiseAll.concat(scripts)
    return scripts
  }
  function loadSource(url) {
    return window.fetch(url).then(res => res.text());
  }
}